package middleware

import (
	"gin-app/utils/response"
	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt/v5"
	"net/http"
	"strings"
)

var jwtKey = []byte("your_secret_key")

func JwtMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		tokenStr := c.Request.Header.Get("Authorization")
		if tokenStr == "" || strings.HasPrefix(tokenStr, "Bearer ") {
			response.Fail(c, http.StatusUnauthorized, "missing token")
			c.Abort()
			return
		}
		tokenStr = strings.TrimPrefix(tokenStr, "Bearer ")
		token, err := jwt.Parse(tokenStr, func(token *jwt.Token) (interface{}, error) {
			return jwtKey, nil
		})
		if err != nil || !token.Valid {
			response.Fail(c, http.StatusUnauthorized, "invalid token")
			c.Abort()
			return
		}
		c.Next()
	}

}
